package com.seari.vehbaseP.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.commonutils.redis.ex.JedisNotInitializeException;
import com.seari.vehbaseP.bean.CommonPartResponse;
import com.seari.vehbaseP.bean.DeviceParamDataBean;
import com.seari.vehbaseP.mapper.DiagramBehaviorMapper;
import com.seari.vehbaseP.service.DiagramBehaviorService;
import com.seari.vehbaseP.utils.LocalDateTimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DiagramBehaviorServiceImpl implements DiagramBehaviorService {

    private Logger logger = LoggerFactory.getLogger(DiagramBehaviorServiceImpl.class);

    @Autowired
    DiagramBehaviorMapper diagramBehaviorMapper;

    /**
     * 获取设备实时数据
     *
     * @param projectCode
     * @param deviceId
     * @return
     */
    @Override
    public CommonPartResponse fetchDeviceRealData(String projectCode, String deviceId) {
        Jedis jedis = null;
        String msg = "";
        try {
            jedis = JedisUtilProxy.getJedis();
            jedis.select(2);

            String param = StringUtils.join(projectCode,"_",deviceId);
            String realData = jedis.get(param);

            JSONArray realDataArray = null;
            if (StringUtils.isNotBlank(realData)) {
                realDataArray = JSONArray.parseArray(realData);
            }

            return CommonPartResponse.success("success", realDataArray);
        } catch (JedisNotInitializeException e) {
            msg = "redis communications link failure.";
            logger.error(e.getMessage());
        } finally {
            jedis.close();
        }
        return CommonPartResponse.failure(msg, null);
    }


    /**
     * 获取设备历史数据
     *
     * @param projectCode
     * @param deviceId
     * @param dataCode
     * @return
     */
    @Override
    public CommonPartResponse fetchDeviceHistoricalData(int projectCode, int deviceId, int dataCode) {

        List<DeviceParamDataBean> deviceParamDataBeans = null;
        List<Double> resData = new ArrayList<>();
        try {
            deviceParamDataBeans = diagramBehaviorMapper.fetchDeviceHistoricalData(projectCode, deviceId, dataCode);
        } catch (Exception e) {
            logger.error("数据库查询异常,[errMsg]={}", e.getMessage());
            return CommonPartResponse.failure("数据库查询异常", null);
        }

        int beansSize = deviceParamDataBeans.size();

        if (beansSize > 0) {

            int currentHours = LocalDateTimeUtils.countNumHoursOfDay() + 1; // 因为取到的当前小时是从0开始

            if (beansSize != currentHours) {
                //有数据缺失
                if (beansSize < currentHours) {
                    // 在正常数据集合中，bean的创建时间属性取到的小时应当是按照0-23排序
                    for (int hourIndex = 0, beanIndex = 0; hourIndex < currentHours; hourIndex++) {

                        if (beanIndex >= beansSize) {
                            resData.add(0.0);
                            continue;
                        }
                        LocalDateTime gmtCreate = deviceParamDataBeans.get(beanIndex).getGmtCreate();
                        if (hourIndex != gmtCreate.getHour()) {
                            resData.add(0.0);
                        } else {
                            double collectData = deviceParamDataBeans.get(beanIndex).getCollectData();
                            resData.add(collectData);
                            beanIndex++;
                        }
                    }
                }

            } else {

                // 正常返回collectdata 数组
                for (DeviceParamDataBean deviceParamDataBean : deviceParamDataBeans) {
                    resData.add(deviceParamDataBean.getCollectData());
                }
            }
        }

        return CommonPartResponse.success("success",resData.size(),resData);
    }
}
